const CryptoJS = require('@/utils/grace.js');

const jsApiCall = (data, cb, errorCb) => {
	WeixinJSBridge.invoke('getBrandWCPayRequest', {
		"appId": data.appId,
		"timeStamp": data.timeStamp,
		"nonceStr": data.nonceStr,
		"package": data.package,
		"signType": data.signType,
		"paySign": data.paySign,
	}, function(res) {
		if (res.err_msg == "get_brand_wcpay_request:ok") {
			cb();
			CryptoJS.navigate('/pages/shoppingCart/success');
		} else {
			errorCb();
			CryptoJS.msg(res.errMsg);
			// CryptoJS.delay(1000, () => {
			// 	CryptoJS.navigate('/pages/shoppingCart/fail')
			// })
		}
	});

}
const pay = (data, cb, errorCb) => {
	data = data || {}

	if (!data.appId || !data.nonceStr || !data.package || !data.paySign || !data.signType || !data.timeStamp) {
		errorCb()
		CryptoJS.msg('支付参数缺失')
		return;
	}
	// #ifdef H5
	var ua = window.navigator.userAgent.toLowerCase();
	if (ua.match(/MicroMessenger/i) == 'micromessenger') {
		if (typeof WeixinJSBridge === 'undefined') {
			if (document.addEventListener) {
				document.addEventListener('WeixinJSBridgeReady', jsApiCall(data, cb, errorCb), false)
			} else if (document.attachEvent) {
				document.attachEvent('WeixinJSBridgeReady', jsApiCall(data, cb, errorCb))
				document.attachEvent('onWeixinJSBridgeReady', jsApiCall(data, cb, errorCb))
			}
		} else {
			jsApiCall(data, cb, errorCb)
		}
	} else {
		CryptoJS.msg('请到微信环境支付！')
		errorCb()
	}
	// #endif
}

module.exports = {
	pay
};
